package org.timemanager.view;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TableRow;
import android.widget.TextView;

/**
 * change or update a event's property
 * @author Dereky
 *
 */
public class EventActivity extends Activity {
	/**
	 * action to add a new event,before filling in,every text box is cleared
	 */
	public static final String ACTION_ADD="org.timemanager.action.event_add";
	/**
	 * action to update a existed event
	 */
	public static final String ACTION_UPDATE="org.timemanager.action.event_update";
	/**
	 * there is no warn by default,
	 * if user choose to warn event in the case of forgetting to end current event,
	 * then the default warn time is this duration(minutes).
	 */
	public static final String DEFAULT_DURATION="60";
	
	/**
	 * action add:0,action update:1
	 */
	private int operateType;
	private DatabaseTool databaseTool;
	
	/**
	 * indicate whether this activity is jumped from widget or main activity.
	 * <br/>
	 * true is from widget,false is from main activity.
	 */
	private boolean fromWidget;
	/**
	 * if the operation is updating,
	 * then store the event id and its all properties to fill in the text box first. 
	 */
	private int eventId;
	private TextView eventTitle;
	private EditText eventName;
	private AutoCompleteTextView eventCategory;
	private CheckBox eventWarn;
	private TableRow eventShow;
	private EditText eventDuration;
	private EditText eventNote;
	private Button eventSave;
	private Button eventStart;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.event_view);
		initAllConfiguration();
		
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try{
			databaseTool.close();
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	/**
	 * initialize all the global parameters.
	 */
	private void initAllConfiguration(){
		databaseTool=new DatabaseTool(EventActivity.this);
		
		fromWidget=false;
		String action=getIntent().getAction();
		if(action.equals(ACTION_ADD)){
			operateType=0;
			fromWidget=getIntent().getBooleanExtra("fromWidget", false);
		}else if(action.equals(ACTION_UPDATE)){
			operateType=1;
			eventId=getIntent().getIntExtra("eventId", -1);
		}
		
		eventTitle=(TextView) findViewById(R.id.event_view_title);
		eventName=(EditText) findViewById(R.id.event_view_name);
		eventCategory=(AutoCompleteTextView) findViewById(R.id.event_view_category);
		setEventCategoryAdapter();
		
		eventWarn=(CheckBox) findViewById(R.id.event_view_warn);
		eventWarn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				if(isChecked){
					eventShow.setVisibility(View.VISIBLE);
				}else{
					eventShow.setVisibility(View.GONE);
				}
			}
		});
		
		eventShow=(TableRow) findViewById(R.id.event_show_duration);
		eventDuration=(EditText) findViewById(R.id.event_view_duration);
		eventNote=(EditText) findViewById(R.id.event_view_note);
		eventSave=(Button) findViewById(R.id.event_view_save);
		eventStart=(Button) findViewById(R.id.event_view_start);
		
		if(operateType==0){
			showEventDuration(false);
			eventTitle.setText(R.string.event_view_add);
			eventSave.setText(R.string.event_button_add);
		}else if(operateType==1){
			eventTitle.setText(R.string.event_view_update);
			eventSave.setText(R.string.event_button_update);
			
			Cursor eventCursor=databaseTool.getEvent(eventId);
			eventCursor.moveToFirst();
			eventName.setText(eventCursor.getString(1));
			eventCategory.setText(eventCursor.getString(3));
			int duration=eventCursor.getInt(4);
			if(duration==-1){
				showEventDuration(false);
			}else{
				showEventDuration(true);
				eventDuration.setText(duration+"");
			}
			eventNote.setText(eventCursor.getString(5));
//			try{
//				eventCursor.close();
//			}catch (Exception e) {
//				// TODO: handle exception
//			}
		}
		
		eventSave.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				operateMode(0);
			}
		});
		eventStart.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				operateMode(1);
			}
		});
	}
	/**
	 * take all operation into account.
	 * @param mode which operation to be acted.
	 * 0 means adding,1 means starting.
	 */
	private void operateMode(int mode){
		String eventNameString=eventName.getText().toString();
		eventNameString=eventNameString.trim();
		if(eventNameString=="" || eventNameString.length()==0){
			Toast.makeText(EventActivity.this, getText(
					R.string.event_view_add_no), Toast.LENGTH_SHORT).show();
			return;
		}
		int checkResult=databaseTool.checkEventName(eventNameString);
		if(checkResult!=-1 && (operateType==0 || 
				operateType==1&&checkResult!=eventId)){
			Toast.makeText(EventActivity.this, getText(
					R.string.event_view_add_exist), Toast.LENGTH_SHORT).show();
			return;
		}
		int duration=-1;
		if(eventWarn.isChecked()){
			String durationString=eventDuration.getText().toString();
			durationString=durationString.trim();
			if(durationString=="" || durationString.length()==0){
				Toast.makeText(EventActivity.this, getText(
						R.string.event_view_duration_no), Toast.LENGTH_SHORT).show();
				return;
			}
			duration=Integer.parseInt(durationString);
		}
		int categoryId=-1;
		boolean bNewCategory=false;
		String eventCategoryString=eventCategory.getText().toString();
		eventCategoryString=eventCategoryString.trim();
		if(eventCategoryString!="" && eventCategoryString.length()!=0){	
			categoryId=databaseTool.checkCategoryName(eventCategoryString);
			if(categoryId==-1){
				bNewCategory=true;
				categoryId=(int) databaseTool.insertCategory(eventCategoryString);
			}
		}
		if(operateType==0){
			eventId=(int) databaseTool.insertEvent(eventNameString, categoryId, 
					duration, eventNote.getText().toString());
			if(mode==0){
				Toast.makeText(EventActivity.this, getText(
						R.string.event_view_add_success), Toast.LENGTH_SHORT).show();
			}
		}
		else if(operateType==1){
			databaseTool.updateEvent(eventId, eventNameString, 
					categoryId, duration, eventNote.getText().toString());
			if(mode==0){
				Toast.makeText(EventActivity.this, getText(
						R.string.event_view_update_success), Toast.LENGTH_SHORT).show();
			}
		}
		if(mode==0){
			if(StartRecord.curEventId==eventId){
				StartRecord.updateCurDoing(EventActivity.this, eventId);
			}
			Bundle bundle=new Bundle();
			bundle.putBoolean("newCategory", bNewCategory);
			if(bNewCategory){
				bundle.putString("categoryName", eventCategoryString);
			}
			bundle.putInt("eventId", eventId);
			bundle.putString("eventName", eventNameString);
			bundle.putInt("categoryId", categoryId);
			Intent intent=new Intent();
			intent.putExtras(bundle);
			setResult(RESULT_OK, intent);
		}
		else if(mode==1){
			if(StartRecord.startRecord(EventActivity.this, 
					eventId, eventNameString)){
				/*
				 * when added a new event item,
				 * then the widget candidate list should be refresh
				 */
				Toast.makeText(EventActivity.this, getText(
						R.string.event_start_success), Toast.LENGTH_SHORT).show();
			}
		}
		/*
		 * whatever a new event is added or updated,
		 * the widget should be updated with new stated
		 */
		TimeManagerWidget.clearItems();
		if(fromWidget){
			/*
			 * there is problem in returning to event list view
			 * when opening the event list view and clicking in the widget to add
			 * now return to a new event list view due to start activity
			 * but after return to the new started activity,
			 * there is difference from the old open activity
			 * then the old open activity should be closed
			 */
			Intent intent=new Intent(EventActivity.this, TimeManagerActivity.class);
			startActivity(intent);
		}
		/*
		 * close this activity and return to event list view
		 */
		
		if(mode==0 && operateType==0){
			eventName.setText("");
			return;
		}
		finish();
	}
	/**
	 * when user decides to warn,then pop up a text box to store the time
	 * @param bShowDuration whether to show the duration text box
	 */
	private void showEventDuration(boolean bShowDuration){
		if(bShowDuration){
			eventWarn.setChecked(true);
			eventShow.setVisibility(View.VISIBLE);
		}else{
			eventWarn.setChecked(false);
			eventShow.setVisibility(View.GONE);
			eventDuration.setText(DEFAULT_DURATION);
		}
	}
	/**
	 * using auto complete text box to list all categories,
	 * and also user can add new category directly.
	 */
	private void setEventCategoryAdapter(){
		ArrayList<String> categoryNameList=new ArrayList<String>();
		Cursor allCategory=databaseTool.getCategories();
		while(allCategory.moveToNext()){
			categoryNameList.add(allCategory.getString(1));
		}
//		try{
//			allCategory.close();
//		}catch (Exception e) {
//			// TODO: handle exception
//		}
		eventCategory.setAdapter(new ArrayAdapter<String>(EventActivity.this, 
				android.R.layout.simple_dropdown_item_1line,
				(String[]) categoryNameList.toArray(new String[categoryNameList.size()])));
	}
}
